<template>
  <ContentWrap>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">收支汇总</div>
      </div>
      <div class="content_main mb-32">
        <div class="table_title">收入汇总</div>
        <el-table :data="formData.data.incomeList">
          <template v-for="item in incomeColumn" :key="item.prop">
            <el-table-column
              :width="item.width"
              :align="item.align ? item.align : 'center'" 
              :label="item.label"
              :prop="item.prop"
            >
              <template #default="scope">
                <div v-if="item.prop === 'mainContractName'" @click="goContract(scope.row.mainContractId)">
                  <span style="color: #409eff;cursor: pointer;">{{ scope.row.mainContractName }}</span>
                </div>
                <div v-else>{{ scope.row[item.prop] ? scope.row[item.prop] : '-' }}</div>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div class="content_main">
        <div class="table_title">支出汇总</div>
        <el-table :data="formData.data.expenditureSummary" :row-class-name="tableRowClassName">
          <template v-for="item in expenseColumn" :key="item.prop">
            <el-table-column
              :width="item.width"
              :align="item.align ? item.align : 'center'" 
              :label="item.label"
              :prop="item.prop"
            >
              <template #default="scope">
                <div 
                  v-if="
                    item.prop === 'expenditureCategory' && 
                    scope.row.expenditureCategory !== '合计' && 
                    scope.row.expenditureCategory !== '管理成本' &&
                    scope.row.expenditureCategory !== '其他成本'
                  " @click="goContract(scope.row.contractId)">
                  <span style="color: #409eff;cursor: pointer;">{{ scope.row.expenditureCategory }}</span>
                </div>
                <div v-else-if="scope.row[item.prop]">{{ scope.row[item.prop] }}</div>
                <div v-else>-</div>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
    </div>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">收入结算</div>
      </div>
      <div class="content_main">
        <el-table :data="formData.data.projectSettlementRespVOS" :row-class-name="tableRowClassName">
          <el-table-column align="center" label="结算时间" prop="settlementTime">
            <template #default="scope">
              <el-date-picker
                style="width: 100%"
                v-if="scope.row.editable"
                v-model="scope.row.settlementTime"
                type="date"
                placeholder="请选择结算时间"
                @change="e => scope.row.settlementTime = formatDateToYMD(e)"
              />
              <div v-else>
                <span v-if="scope.row.settlementTime">{{ scope.row.settlementTime }}</span>
                <span v-else>-</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="结算金额（含税）" prop="amountWithTax" >
            <template #default="scope">
              <el-input-number
                style="width: 100%"
                controls-position="right" 
                v-if="scope.row.editable" 
                :min="0" 
                v-model="scope.row.amountWithTax" 
                @input="e => amountWithTaxChange(e, scope.$index)"
                placeholder="请输入结算金额（含税）"
              />
                <div v-else>{{ scope.row.amountWithTax }}</div>
              </template>
            </el-table-column>
          <el-table-column align="center" label="税率" prop="taxRate">
            <template #default="scope">
              <el-input-number
                style="width: 100%" 
                controls-position="right" 
                v-if="scope.row.editable" 
                :min="0" 
                v-model="scope.row.taxRate" 
                @input="e => taxRateChange(e, scope.$index)"
                placeholder="请输入税率" 
              />
              <div v-else>
                <span v-if="scope.row.settlementTime === '合计'"></span>
                <span v-else>{{ scope.row.taxRate }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="结算金额（不含税）" prop="amountWithoutTax" >
            <template #default="scope">
              <el-input-number style="width: 100%" controls-position="right" v-if="scope.row.editable" disabled v-model="scope.row.amountWithoutTax" placeholder="请输入结算金额（不含税）" />
              <div v-else>{{ scope.row.amountWithoutTax }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="发票" prop="invoice">
            <template #default="scope">
              <div v-if="scope.row.settlementTime === '合计'"></div>
              <div v-else>
                <div v-if="scope.row.editable">
                  <div class="flex-s" v-if="scope.row.invoice">
                    <span class="!w-160px ellipsis">{{ scope.row.invoice.slice(scope.row.invoice.lastIndexOf('/') + 1) }}</span>
                    
                    <span class="mx-12">
                      <el-upload
                          :http-request="e => requestTable(e, scope.$index)"
                          :show-file-list="false"
                          :before-upload="beforeUpload"
                        >
                          <template #trigger><a href="#">修改</a></template>
                        </el-upload>
                    </span>
                    <a :href="scope.row.invoice">下载</a>
                  </div>
                  
                  <el-upload
                    v-else
                    :http-request="e => requestTable(e, scope.$index)"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                  >
                    <template #trigger><a href="#">上传附件</a></template>
                  </el-upload>
  
                </div>
                <div class="flex-s" v-else>
                  <div class="!w-180px ellipsis">{{ scope.row.invoice.slice(scope.row.invoice.lastIndexOf('/') + 1) }}</div>
                  <a class="ml-12" :href="scope.row.invoice">下载</a>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :width="200" align="center" label="操作">
            <template #default="scope">
              <div v-if="scope.row.settlementTime === '合计'"></div>
              <div v-else>
                <div v-if="scope.row.editable">
                  <el-button link type="info" @click="cancle(scope.$index)">取消</el-button>
                  <el-button link type="primary" @click="save(scope.row, scope.$index)">保存</el-button>
                </div>
                <div v-else>
                  <el-button link type="primary" @click="edit(scope.$index)">
                    编辑
                  </el-button>
                  <el-popconfirm
                    class="box-item"
                    title="确定删除？"
                    placement="top-end"
                    @confirm="del(scope.row.id, scope.$index)"
                  >
                    <template #reference>
                      <el-button link type="danger">
                        删除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-button class="addRow" @click="addRow" plain>
          <el-icon class="mr-6"><Plus /></el-icon>  添加
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">支出明细</div>
      </div>

      <el-table :data="formData.data.expenditureDetailList" :row-class-name="tableRowClassName">
        <template v-for="item in expenseDetailColumn" :key="item.prop">
          <el-table-column
            :width="item.width"
            :align="item.align ? item.align : 'center'" 
            :label="item.label"
            :prop="item.prop"
          >
            <template #default="scope">
              <div v-if="item.prop === 'paymentTime' && scope.row.paymentTime !== '合计'">{{ scope.row.paymentTime ? formatDate(scope.row.paymentTime) : '-'}}</div>
              <div v-else-if="scope.row[item.prop]">

                <div v-if="item.prop === 'applicationNumber'" @click="goExpenseDetail(scope.row.expenseId)">
                  <span style="color: #409eff;cursor: pointer;">{{ scope.row.applicationNumber }}</span>
                </div>
                <div v-else>{{ scope.row[item.prop] }}</div>
                
              </div>
              <div v-else>
                <div v-if="scope.row.paymentTime === '合计'"></div>
                <div v-else>
                  {{ formatDate(scope.row.paymentTime) }}
                </div>
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
  </ContentWrap>
</template>
<script setup>
  import {ref,reactive,nextTick} from "vue"
  import { Plus } from '@element-plus/icons-vue'
  import { formatDateToYMD, parseYMDToDate } from '@/utils/index'
  import * as ProjectApi from '@/api/viewsApi/project'
  import { incomeColumn, expenseColumn, expenseDetailColumn } from './jsonAndRules'
  import { formatDate } from '@/utils/formatTime'
  import { updateFile } from "@/api/infra/file/index.ts"
  const router = useRouter()
  const loading = ref(false)
  const projectId = ref(null)
  const formData = reactive({
    data: {
      incomeList: [],
      expenditureSummary: [],
      projectSettlementRespVOS: [],
      expenditureDetailList: [],
    }
  })
  const copyData = ref([])
  /** 查询详情信息 */
  const init = async (id) => {
    projectId.value = id
    loading.value = true
    try {
      const data = await ProjectApi.getProjectSettlement(id)
      data.incomeList = [{
        mainContractName: data.mainContractName,
        totalContractAmount: (data.totalContractAmount / 100).toFixed(2), // 合同金额(含税)
        accumulatedSettledAmount: (data.accumulatedSettledAmount / 100).toFixed(2), // 累计已结算金额(含税)
        unsettledAmount: (data.unsettledAmount / 100).toFixed(2), // 未结算金额(含税)
      }]

      delete data.mainContractName
      delete data.totalContractAmount
      delete data.accumulatedSettledAmount
      delete data.unsettledAmount
      if(data.expenditureSummary && data.expenditureSummary.length > 0) {
        data.expenditureSummary.forEach(item => {
          item.totalChangeableAmount = (item.totalChangeableAmount / 100).toFixed(2)
          item.totalPaidAmount = (item.totalPaidAmount / 100).toFixed(2)
          item.totalUnpaidAmount = (item.totalUnpaidAmount / 100).toFixed(2)
        })
      }
      if(data.expenditureDetailList && data.expenditureDetailList.length > 0) {
        data.expenditureDetailList.forEach(item => {
          item.paymentAmountWithTax = (item.paymentAmountWithTax / 100).toFixed(2)
          item.paymentAmountWithoutTax = (item.paymentAmountWithoutTax / 100).toFixed(2)
        })
      }
      if(data.projectSettlementRespVOS && data.projectSettlementRespVOS.length > 0) {
        data.projectSettlementRespVOS.forEach(item => {
          item.amountWithTax = (item.amountWithTax / 100).toFixed(2)
          item.amountWithoutTax = (item.amountWithoutTax / 100).toFixed(2)
          item.editable = false
        })
      }
  
      formData.data = data
      modalAmount()
      incomeComputedAmount()
      expenseAmount()

    } finally {
      loading.value = false
    }


  }
  const tableRowClassName = ({ row, rowIndex }) => {
    if (
      row.expenditureCategory === '合计' || 
      row.settlementTime === '合计' ||
      row.paymentTime === '合计'
    ) {
      return "bg-black"
    }
  }
  // 跳转合同详情
  const goContract = (id) => {
    router.push({
      path: '/contract',
      query: {
        id,
      }
    })
  }
  // 跳转费用详情
  const goExpenseDetail = (id) => {
    router.push({
      path: '/financial/expenditure/index',
      query: {
        id,
      }
    })
  }
  /**
   * 收入结算逻辑处理 - 开始
  */

  const amountWithTaxChange = (e, index) => {
    let taxRate = formData.data.projectSettlementRespVOS[index].taxRate
    let amountWithoutTax = (e - (e * taxRate / 100)).toFixed(2)
    formData.data.projectSettlementRespVOS[index].amountWithoutTax = amountWithoutTax
  }
  const taxRateChange = (e, index) => {
    let amountWithTax = formData.data.projectSettlementRespVOS[index].amountWithTax
    let amountWithoutTax = (amountWithTax - (amountWithTax * e / 100)).toFixed(2)
    formData.data.projectSettlementRespVOS[index].amountWithoutTax = amountWithoutTax
  }

  const requestTable = async (options, index) => {
    const upFilesData = new FormData()
    upFilesData.append('file', options.file)
    try {
      const res = await updateFile(upFilesData)
      formData.data.projectSettlementRespVOS[index].invoice = res.data
    }finally {
      
    }
  }
  // 文件上传之前判断
  const beforeUpload = (file) => {
    let fileExtension = ''
    if (file.name.lastIndexOf('.') > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
    }
    
    const fileType = ['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']
    const isImg = fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true
      return !!(fileExtension && fileExtension.indexOf(type) > -1)
    })
    const isLimit = file.size < 20 * 1024 * 1024
    if (!isImg) {
      ElMessage.error(`文件格式不正确, 请上传${fileType.join('/')}格式!`)
      return false
    }
    if (!isLimit) {
      ElMessage.error(`上传文件大小不能超过${20}MB!`)
      return false
    }
  }

  const addRow = () => {
    let projectSettlementRespVOS = JSON.parse(JSON.stringify(formData.data.projectSettlementRespVOS))
    copyData.value = JSON.parse(JSON.stringify(projectSettlementRespVOS))
    let flag = projectSettlementRespVOS.find(item => item.editable)
    if (flag) {
      ElMessage.warning('请先保存当前数据')
      return
    }
    let tableItem = ({
      settlementTime: '',
      amountWithTax: null,
      taxRate: null,
      amountWithoutTax: null,
      invoice: '',
      editable: true,
    })
    projectSettlementRespVOS.splice(projectSettlementRespVOS.length - 1, 0, tableItem);
    formData.data.projectSettlementRespVOS = projectSettlementRespVOS
  }

  const edit = (index) => {
    let projectSettlementRespVOS = JSON.parse(JSON.stringify(formData.data.projectSettlementRespVOS))
    let flag = projectSettlementRespVOS.find(item => item.editable)
    if (flag) {
      ElMessage.warning('请先保存当前数据')
      return
    }
    copyData.value = JSON.parse(JSON.stringify(projectSettlementRespVOS))
    console.log(copyData.value);
    projectSettlementRespVOS[index].editable = true
    formData.data.projectSettlementRespVOS = projectSettlementRespVOS
    incomeComputedAmount()
  }

  const del = async (id, index) => {
    let projectSettlementRespVOS = JSON.parse(JSON.stringify(formData.data.projectSettlementRespVOS))
    try {
      await ProjectApi.deleteProjectSettlement({ids: id})
      projectSettlementRespVOS.splice(index, 1)
      formData.data.projectSettlementRespVOS = projectSettlementRespVOS
      incomeComputedAmount()
    } finally{
      
    }
  }

  const cancle = () => {
    let projectSettlementRespVOS = JSON.parse(JSON.stringify(copyData.value))
    formData.data.projectSettlementRespVOS = projectSettlementRespVOS
  }

  const save = async (row, index) => {
    let projectSettlementRespVOS = JSON.parse(JSON.stringify(formData.data.projectSettlementRespVOS))

    const {amountWithTax, taxRate, amountWithoutTax, invoice, settlementTime} = row
    if (!settlementTime) {
      ElMessage.warning('请选择结算时间')
      return
    }
    if (!amountWithTax) {
      ElMessage.warning('请输入含税金额')
      return
    }
    if (!taxRate) {
      ElMessage.warning('请输入税率')
      return
    }
    if (!invoice) {
      ElMessage.warning('请上传发票')
      return
    }

    let parms = {
      id: row.id,
      projectId: projectId.value,
      amountWithTax: amountWithTax * 100,
      taxRate: taxRate,
      amountWithoutTax: amountWithoutTax * 100,
      invoice: invoice,
      settlementTime: settlementTime,
    }

    if(!row.id){
      delete parms.id
      try {
        await ProjectApi.addProjectSettlement([parms])
        projectSettlementRespVOS.forEach(item => item.editable = false)
        formData.data.projectSettlementRespVOS = projectSettlementRespVOS
        await init(projectId.value)
        incomeComputedAmount()
      } finally{
        
      }
    }else{
      try {
        await ProjectApi.editProjectSettlement([parms])
        projectSettlementRespVOS.forEach(item => item.editable = false)
        formData.data.projectSettlementRespVOS = projectSettlementRespVOS
        await init(projectId.value)
        incomeComputedAmount()
      } finally{
        
      }
      
    }

  }
  /**
   * 收入结算逻辑处理 - 结束
   */



  // 支出汇总合计
  function modalAmount() {
    var filterData = formData.data.expenditureSummary.filter(item => item.expenditureCategory !== '合计')
    
    let totalChangeableSum = 0
    let totalPaidSum = 0
    let totalUnpaidSum = 0
    for(let item of filterData){
        totalChangeableSum += Number(item.totalChangeableAmount)
        totalPaidSum += Number(item.totalPaidAmount)
        totalUnpaidSum += Number(item.totalUnpaidAmount)
    }

    totalChangeableSum = totalChangeableSum.toFixed(2)
    totalPaidSum = totalPaidSum.toFixed(2)
    totalUnpaidSum = totalUnpaidSum.toFixed(2)

    filterData.push({
        id: 0,
        expenditureCategory: '合计',
        totalChangeableAmount: totalChangeableSum > 0 ? totalChangeableSum : '0.00',
        totalPaidAmount: totalPaidSum > 0 ? totalPaidSum : '0.00',
        totalUnpaidAmount: totalUnpaidSum > 0 ? totalUnpaidSum : '0.00',
    })
    
    formData.data.expenditureSummary = filterData
  }
  // 收入结算合计
  function incomeComputedAmount() {
    let filterData = formData.data.projectSettlementRespVOS.filter(item => item.settlementTime !== '合计')

    let amountWithTaxSum = 0
    let amountWithoutTaxSum = 0
    for(let item of filterData){
        amountWithTaxSum += Number(item.amountWithTax)
        amountWithoutTaxSum += Number(item.amountWithoutTax)
    }

    amountWithTaxSum = amountWithTaxSum.toFixed(2)
    amountWithoutTaxSum = amountWithoutTaxSum.toFixed(2)

    filterData.push({
        id: 0,
        settlementTime: '合计',
        amountWithTax: amountWithTaxSum > 0 ? amountWithTaxSum : '0.00',
        taxRate: '',
        amountWithoutTax: amountWithoutTaxSum > 0 ? amountWithoutTaxSum : '0.00',
        invoice: '',
    })
    
    formData.data.projectSettlementRespVOS = filterData
  }
  function expenseAmount() {
    let filterData = formData.data.expenditureDetailList.filter(item => item.paymentTime !== '合计')

    let payWithTaxSum = 0
    let payWithoutTaxSum = 0
    for(let item of filterData){
        payWithTaxSum += Number(item.paymentAmountWithTax)
        payWithoutTaxSum += Number(item.paymentAmountWithoutTax)
    }

    payWithTaxSum = payWithTaxSum.toFixed(2)
    payWithoutTaxSum = payWithoutTaxSum.toFixed(2)

    filterData.push({
        id: 0,
        paymentTime: '合计',
        applicationNumber: '',
        paymentItemName: '',
        paymentAmountWithTax: payWithTaxSum > 0 ? payWithTaxSum : '0.00',
        taxRate: '',
        paymentAmountWithoutTax: payWithoutTaxSum > 0 ? payWithoutTaxSum : '0.00',
        receivingUnit: '',
    })
    
    formData.data.expenditureDetailList = filterData
  }
  
  defineExpose({
    init,
  })
  
</script>
<style lang="scss" scoped>
.content{
    width: 100%;
    min-height: 80px;
    padding: 6px;
    margin-bottom: 24px;
    // border-right: 1px solid #eee;
    box-sizing: border-box;
    .content_head {
        margin-bottom: 24px;
        .line {
            width: 5px;
            height: 21px;
            background: #50B5FF;
        }
        .title {
            font-size: 18px;
            color: #333;
            margin-left: 12px;
            font-weight: 600;
        }
    }
    .content_main {
        width: 100%;
        padding: 0 32px;
        box-sizing: border-box;
    }
}
  ::v-deep .bg-black {
      background-color: #F2F2F2;
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 14px;
      color: #1D1D1D;
  }

.addRow{
  margin-top: 12px;
  width: 100%;
}
</style>
